package com.kly.user.task.service;

import com.alibaba.fastjson.JSONObject;
import com.fqgj.common.utils.CollectionUtils;
import com.fqgj.log.factory.LogFactory;
import com.fqgj.log.interfaces.Log;
import com.google.common.collect.Maps;
import com.google.common.eventbus.AsyncEventBus;
import com.kly.enums.ParameterTypeEnum;
import com.kly.user.db.dao.TMessagePushDao;
import com.kly.user.db.entity.TMessagePushEntity;
import com.kly.user.db.entity.UserTaskJobEntity;
import com.kly.user.enums.AppEnum;
import com.kly.user.eventbus.ActionEnum;
import com.kly.user.eventbus.Event;
import com.kly.user.task.ExecuteHandler;
import com.kly.user.task.ExecuteResult;
import com.kly.user.task.enums.PushTypeEnum;
import com.kly.user.task.enums.TaskStatusEnum;
import com.kly.user.task.enums.TaskTypeEnum;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
import java.util.Map;


@Service("appMessagePushImpl")
public class AppMessagePushImpl implements ExecuteHandler {
    private static Log logger = LogFactory.getLog("taskFileLog");

    @Resource
    AsyncEventBus asyncEventBus;

    @Override
    public TaskTypeEnum getType() {
        return TaskTypeEnum.APP_MESSAGE_PUSH;
    }

    @Override
    public <T> ExecuteResult doExecute(T t) throws Exception {

        UserTaskJobEntity entity = (UserTaskJobEntity) t;
        logger.info("app message push job starting, job detail:{}", JSONObject.toJSONString(entity));

        final List<TMessagePushEntity> pushRecords = queryWaitingPushRecords();
        if (CollectionUtils.isEmpty(pushRecords)) {
            logger.info("app message push job starting, job detail: NO_CHATTER_EXISTS");
            return ExecuteResult.builder().jobId(entity.getId()).resultMsg("success").resultCode(TaskStatusEnum.SUCCESS.getCode()).taskType(TaskTypeEnum.NOTICE_PUSH.getCode()).build();
        }
        for (TMessagePushEntity o : pushRecords) {

            if (PushTypeEnum.LIKE_BACK.getCode().equals(o.getMsgType())) {
                pushNewMatchMessage(o.getFromUserCode(), o.getToUserCode(), AppEnum.fromType(String.valueOf(o.getToApp())));
            }
            if (PushTypeEnum.WHO_LIKE_ME.getCode().equals(o.getMsgType())) {
                pushNewWLMMessage(o.getFromUserCode(), o.getToUserCode(), AppEnum.fromType(String.valueOf(o.getToApp())));
            }


            o.setStatus(1);
            messagePushDao.updateByPrimaryKey(o);
        }


        logger.info("app message push job end");
        return ExecuteResult.builder().jobId(entity.getId()).resultMsg("success").resultCode(TaskStatusEnum.SUCCESS.getCode()).taskType(TaskTypeEnum.NOTICE_PUSH.getCode()).build();
    }

    private void pushNewWLMMessage(String fromUseCode, String toUserCode, AppEnum appEnum) {
        asyncEventBus.post(buildWLMEvent(fromUseCode, toUserCode, appEnum));
    }

    private Event buildWLMEvent(String fromUseCode, String toUserCode, AppEnum appEnum) {
        Map<String, Integer> params = Maps.newHashMap();
        params.put("type", ParameterTypeEnum.WHO_LIKE_ME.getId());
        return Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).fromUserCode(fromUseCode).toUserCode(toUserCode)
                .app(appEnum).content(JSONObject.toJSONString(params)).build();
    }

    private void pushNewMatchMessage(String fromUserCode, String toUserCode, AppEnum appEnum) {
        asyncEventBus.post(buildEvent(fromUserCode, toUserCode, appEnum));
    }


    private Event buildEvent(String fromUserCode, String toUserCode, AppEnum appEnum) {
        Map<String, Integer> params = Maps.newHashMap();
        params.put("type", ParameterTypeEnum.MATCHED_PUSH.getId());
        return Event.builder().eventActionEnum(ActionEnum.PUSH_MSG).fromUserCode(fromUserCode)
                .toUserCode(toUserCode).app(appEnum).content(JSONObject.toJSONString(params)).build();
    }

    @Resource
    TMessagePushDao messagePushDao;
    private List<TMessagePushEntity> queryWaitingPushRecords() {
        Map<String, Object> params = Maps.newHashMap();
        params.put("status", 0);
        return messagePushDao.selectByParams(params);
    }

}
